// pages/TradingArea/GiftBagDetail.js
const controller = require("../controllers/Controller").controller
const url = require("../../utils/kzj.request").url


// 创建一个音频组件
const myAudio = wx.createInnerAudioContext()




const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponBagId: "",
    detail: "",
    shopDetail: "",
    showDialog: false,
    shopkey: "",
    shopMsg: "",
    show: false,
    redId: '',
    redShow: false,
    closeAnimate: false,
    isReceived: false,
    pinSuccess: false,
    canPay: true,
    baseUrl: "",
    userList: [],
    pageNumber: 1,
    pageSize: 8,
    lastPage: false,
    buyNum: "",
    rankPageNumber: 1,
    rankLastPage: false,
    rankList: [],
    swiperNum: 5,
    pageY: 0,
    defineImg: false,
    dialogData: {},

    isPlayVideo: false,
    isPlay: true,
    playSrc: "/assets/tradingArea/audioPlay.png",
    pauseSrc: "/assets/tradingArea/audioPause.png",

    isFromMyCenterVideo: false
  },

  // 截获竖向滑动
  // 静止轮播图滑动，手动设置页面在轮播图上的滑动
  catchTouchMove(e) {
    let Y = this.data.pageY - e.touches[0].clientY
    wx.pageScrollTo({
      scrollTop: Y,
      duration: 0,
    })
  },
  touchstart(e) {
    this.setData({
      pageY: e.touches[0].pageY

    })
  },


  // 用户奖励累计金额分页信息
  accountTotalRewardPage() {
    let value = {}
    value.couponBagId = this.data.couponBagId
    value.pageNumber = this.data.rankPageNumber
    controller.accountTotalRewardPage(value).then(res => {
      console.log(res.data.list);

      if (res.data.list.length > 5) {
        this.setData({
          swiperNum: 5
        })
      } else {
        this.setData({
          swiperNum: res.data.list.length
        })
      }
      res.data.list.forEach(item => {
        if (item.nick) {
          item.nick = item.nick.slice(0, 2) + '****' + item.nick.slice(item.nick.length - 1)
        }
      })

      this.setData({
        rankList: res.data.list,
        rankLastPage: res.data.lastPage
      })
    })
  },

  getRankMore(e) {
    let that = this
    let index = e.detail.current
    if (index == that.data.rankList.length - 6) {
      if (this.data.rankLastPage == false) {
        let value = {}
        value.couponBagId = this.data.couponBagId
        value.pageNumber = this.data.rankPageNumber + 1
        this.setData({
          rankPageNumber: value.pageNumber
        })
        controller.accountTotalRewardPage(value).then(res => {
          res.data.list.forEach(item => {
            if (item.nick) {
              item.nick = item.nick.slice(0, 2) + '****' + item.nick.slice(item.nick.length - 1)
            }
          })
          let list = this.data.rankList
          let list2 = res.data.list
          let list3 = list.concat(list2)
          this.setData({
            rankList: list3,
            rankLastPage: res.data.lastPage
          })
        })
      }
    }
  },


  // 跳转活动报名
  toSignUp() {
    wx.navigateTo({
      url: '/pages/TradingArea/signUpActivity',
    })
  },

  //跳转店铺详情
  toShopDetail(e) {
    let shopId = e.currentTarget.dataset.shopid
    wx.navigateTo({
      url: '/pages/Index/Index?shopId=' + shopId,
    })
  },
  phone(e) {
    let phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },

  //获取店铺详情
  getShopDetail(id) {
    controller.shopDetails({
      shopId: id
    }).then(res => {
      this.setData({
        shopMsg: res.data
      })
    })
  },

  //获取商圈活动用户购买列表
  getUserPayPage() {
    let value = {}
    value.couponBagId = this.data.couponBagId
    value.pageNumber = this.data.pageNumber
    value.pageSize = 8
    controller.getUserPayPage(value).then(res => {

      res.data.list.forEach(item => {
        item.nick = item.nick.split('')[0] + "***"
        item.createTime = item.createTime.substr(5, 11)
      })

      this.setData({
        userList: res.data.list,
        lastPage: res.data.lastPage,
        buyNum: res.data.totalRow
      })
    })
  },

  loadMore() {
    if (this.data.lastPage == false) {
      let value = {}
      value.pageNumber = this.data.pageNumber + 1
      this.setData({
        pageNumber: value.pageNumber
      })
      value.couponBagId = this.data.couponBagId
      value.pageSize = 8
      controller.getUserPayPage(value).then(res => {
        res.data.list.forEach(item => {
          item.nick = item.nick.split('')[0] + "***"
          item.createTime = item.createTime.substr(5, 11)

        })
        let list = this.data.userList
        let list2 = res.data.list
        let list3 = list.concat(list2)
        this.setData({
          userList: list3,
          lastPage: res.data.lastPage
        })
      })
    }
  },

  //跳转商品详情
  toGoodsDetail(e) {
    let shopId = e.currentTarget.dataset.shopid
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/myCenter/shopGoodsDetail?shopId=' + shopId + "&id=" + id,
    })
  },

  //礼券包详情 2.0
  getBagActivityDetail() {
    console.log("礼券包详情 2.0礼券包详情 2.0");
    let that = this
    controller.getActivityDetail({
      couponBagId: this.data.couponBagId
    }).then(res => {
      res.data.vipList.forEach(item => {
        item.isCard = 1
      })
      let list = []
      let cardList = res.data.vipList
      let data = res.data
      if (data.effectiveStartTime) {
        data.effectiveStartTime = res.data.effectiveStartTime.split(" ")[0].replace(/-/g, '.')
        data.effectiveEndTime = res.data.effectiveEndTime.split(" ")[0].replace(/-/g, '.')
      }
      if (data.startTime) {
        data.startTime = res.data.startTime.split(" ")[0].replace(/-/g, '.')
        data.endTime = res.data.endTime.split(" ")[0].replace(/-/g, '.')
      }

      if (data.posterImg && data.posterImg != 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/o2o/qrcode/defaultPoster.jpg') {
        this.setData({
          defineImg: true
        })
      }

      // res.data.video = 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20220517/976161372372992000.mp4'
console.log("礼券包详情",data);
      this.setData({
        detail: data,
        type: data.type,
      })

      // 初始化音频
      if (data.music) {
        this.initMyAudio(data.music)
      }

      // 播放视频
      if (data.video && this.data.isPlayVideo) {
        this.toVideoPage()
      }

      if (data.type == 2 || data.type == 3 || data.type == 4 || data.type == 5) {
        that.getShopDetail(data.shopId)
      }
      if (res.data.couponMap) {
        this.setData({
          shopkey: Object.keys(res.data.couponMap)
        })
        this.data.shopkey.forEach(item => {
          for (let i = 0; i < res.data.couponMap[item].length; i++) {
            list.push(res.data.couponMap[item][i])
          }
        })
      }

      list = list.concat(cardList)

      //优惠券list分组
      let fzLength = parseInt(list.length / 2)
      let fzList = []
      let num = 0
      for (let i = 0; i < fzLength; i++) {
        let itemList = []
        itemList.push(list[num])
        itemList.push(list[num + 1])
        num = num + 2
        fzList.push(itemList)
      }
      if (list.length % 2 != 0) {
        let lzList = []
        lzList.push(list[list.length - 1])
        fzList.push(lzList)
      }

      // 引流卡list分组
      // let cardfzLength = parseInt(cardList.length / 2)
      // let cardFzList = []
      // let cardNum = 0
      // for (let i = 0; i < cardfzLength; i++) {
      //   let itemList = []
      //   itemList.push(cardList[cardNum])
      //   itemList.push(cardList[cardNum + 1])
      //   cardNum = cardNum + 2
      //   cardFzList.push(itemList)
      // }
      // if (cardList.length % 2 != 0) {
      //   let cardLzList = []
      //   cardLzList.push(cardList[list.length - 1])
      //   cardFzList.push(cardLzList)
      // }


      this.setData({
        couponList: fzList,
      })
    })

    console.log("分享参数")
    console.log(this.data.invitationAccountId)
  },

  //获取礼包轮播图
  // getSwiperImg(){
  //   if(this.data.type==1){
  //     controller.getSwiperImg({shopGroupId:this.data.shopGroupId}).then(res=>{
  //       this.setData({
  //         imgList:res.data
  //       })
  //     })
  //   }
  // },
  //生成拼团购买
  createGroupWorkOrder() {
    let that = this
    if (this.data.canPay == false) {
      return
    }
    let value = {}
    value.couponBagId = this.data.couponBagId
    value.sessionId = wx.getStorageSync('usertoken')
    this.setData({
      canPay: false
    })
    wx.request({
      url: url + "/api/order/shopGroupPinOrder",
      method: 'POST',
      data: value,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if (res.statusCode == 200) {
          that.setData({
            canPay: true
          })
          if (res.data.code == 1) {
            let data = res.data.data
            that.pay(data)
          } else if (res.data.code == 2) {
            wx.setStorageSync('usertoken', '')
          } else if (res.data.code == 3) {
            wx.setStorageSync('usertoken', '')
          } else {
            wx.showToast({
              title: res.data.desc,
              icon: 'none',
              duration: 800
            });
          }
        } else {
          wx.showToast({
            title: '[' + res.code + '] 服务器出错,请重试',
            icon: 'none',
            duration: 800
          });
        }
      }
    })
  },
  openDialog() {
    const dialogData = {
      price: this.data.detail.price,
      num: this.data.detail.num,
    }
    this.setData({
      showDialog: true,
      dialogData
    })
  },
  closeDialog() {
    this.setData({
      showDialog: false,
    })
  },
  // 一卡通、店铺爆款、欢乐拼进入单独页面购买
  toBuyPage() {
    const detail = this.data.detail
    let invitationAccountId = this.data.invitationAccountId || ''
    if (detail.num == 0) {
      wx.showToast({
        title: '库存不足，无法购买',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: './buyGiftBag?detail=' + JSON.stringify(this.data.detail) + "&invitationAccountId=" + invitationAccountId,
    })
  },
  buyNow() {
    const type = this.data.detail.type
    const payType = this.data.detail.payType
    if ((type == 0 || type == 2 || type == 3) && payType === 0) {
      // this.openDialog()
      this.toBuyPage()
    } else {
      this.createCouponOrder()
    }
  },
  //生成订单购买
  createCouponOrder(e) {
    let that = this
    if (this.data.canPay == false) {
      return
    }

    let value = {}
    if (e && e.detail) value.num = e.detail

    value.couponBagId = this.data.couponBagId
    if (this.data.invitationAccountId) {
      value.invitationAccountId = this.data.invitationAccountId
    }
    value.sessionId = wx.getStorageSync('usertoken')
    this.setData({
      canPay: false
    })
    console.log(this.data.canPay)
    wx.request({
      url: url + "/api/order/couponOrder",
      method: 'POST',
      data: value,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if (res.statusCode == 200) {
          that.setData({
            canPay: true
          })
          if (res.data.code == 1) {
            let data = res.data.data
            that.pay(data)
          } else if (res.data.code == 2) {
            wx.setStorageSync('usertoken', '')
          } else if (res.data.code == 3) {
            wx.setStorageSync('usertoken', '')
          } else {
            wx.showToast({
              title: res.data.desc,
              icon: 'none',
              duration: 800
            });
          }
        } else {
          wx.showToast({
            title: '[' + res.code + '] 服务器出错,请重试',
            icon: 'none',
            duration: 800
          });
        }
      }
    })


    // controller.createCouponOrder(value).then(res => {
    //   let data = res.data
    //   this.pay(data)
    // })
  },

  pay(data) {
    let that = this
    let value = {}
    value.openId = app.globalData.openId
    value.orderNo = data.orderNo
    value.type = "GC"
    controller.weChatPay(value).then(res => {
      let data = JSON.parse(res.data)
      wx.requestPayment({
        nonceStr: data.nonceStr,
        package: data.package,
        paySign: data.paySign,
        timeStamp: data.timeStamp,
        signType: data.signType,
        success(res) {
          wx.showToast({
            title: "支付成功",
            icon: 'none',
            duration: 1000
          });
          if (that.data.detail.type == 3) {

          } else {
            setTimeout(function () {
              wx.showActionSheet({
                itemList: ['去查看', '继续浏览'],
                success(res) {
                  let index = res.tapIndex
                  console.log(res)
                  if (index == 0) {
                    console.log(that.data.detail.type);
                    wx.reLaunch({
                      url: '/pages/myCenter/myCenter?type=' + that.data.detail.type,
                    })
                  } else {
                    wx.reLaunch({
                      url: '/pages/TradingArea/moreShopCircle?id=' + that.data.detail.shopGroupId,
                    })
                  }
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }, 1500)
          }
        },
        fail(res) {
          wx.showToast({
            title: "支付失败",
            icon: 'none',
            duration: 1000
          });
        },
        complete() {
          that.setData({
            canPay: true
          })
        }
      })
    })
  },

  //获取弹窗消息
  // getMsg() {
  //   let that = this
  //   controller.getNotice().then(res => {
  //     this.setData({
  //       msg: res.data,
  //       show: true
  //     })

  //     setTimeout(function () {
  //       that.setData({
  //         show: false
  //       })
  //     }, 6500)
  //   })
  // },

  //关闭红包
  closeRed() {
    let that = this
    this.setData({
      closeAnimate: false
    })
    setTimeout(function () {
      that.setData({
        redShow: false,
        closeAnimate: false,
        isReceived: false,
        pinSuccess: false,
      })
      that.setData({
        redTimer: setInterval(function () {
          let page = getCurrentPages()
          if (page[page.length - 1].route != 'pages/TradingArea/GiftBagDetail') {
            return
          }
          that.pinList()
        }, 12000)
      })
    }, 280)
  },

  //获取用户未读拼团
  pinList() {
    let that = this
    controller.pinList().then(res => {
      if (res.data.length > 0) {
        this.setData({
          redList: res.data
        })
        if (res.data.length > 0) {
          that.setData({
            redShow: true,
            closeAnimate: true
          })
          clearInterval(that.data.redTimer)
          if (res.data[0].state == 1) {
            this.setData({
              pinSuccess: true,
              readPinOrderNo: this.data.redList[0].orderNo
            })
          } else {
            this.setData({
              pinSuccess: false,
              redId: this.data.redList[0].transactionId,
              redPrice: this.data.redList[0].redMoney
            })
          }
        }
      }
    })
  },

  //领取红包
  giveTransactionRed() {
    if (this.data.redList.length > 0) {
      let value = {}
      value.transactionId = this.data.redId
      controller.giveTransactionRed(value).then(res => {
        wx.showToast({
          icon: 'none',
          title: '领取成功',
        })
        this.setData({
          isReceived: true
        })
      })
    }
  },

  toMyCenter() {
    this.setData({
      redShow: false,
      closeAnimate: false,
      isReceived: false
    })
    if (this.data.type == 3) {
      this.setData({
        redTimer: setInterval(function () {
          let page = getCurrentPages()
          if (page[page.length - 1].route != 'pages/TradingArea/GiftBagDetail') {
            return
          }
          that.pinList()
        }, 6000)
      })
    }
    //消除拼团成功弹出数据
    controller.readPin({
      orderNo: this.data.readPinOrderNo
    }).then(res => {
      wx.navigateTo({
        url: '/pages/myCenter/myCenter',
      })
    })
  },
  toMyAccount() {
    this.setData({
      redShow: false,
      closeAnimate: false,
      isReceived: false
    })
    if (this.data.type == 3) {
      this.setData({
        redTimer: setInterval(function () {
          let page = getCurrentPages()
          if (page[page.length - 1].route != 'pages/TradingArea/GiftBagDetail') {
            return
          }
          that.pinList()
        }, 6000)
      })
    }
    wx.navigateTo({
      url: '/pages/myCenter/myAccount',
    })
  },

  //  初始化音频
  initMyAudio(src) {
    myAudio.src = src
    myAudio.autoplay = true
    myAudio.loop = true
    myAudio.play()
    myAudio.onPlay(() => {
      console.log("播放");
    })
    myAudio.onPause(() => {
      console.log("暂停");
    })
  },
  audioPause() {
    const isPlay = !this.data.isPlay
    isPlay ? myAudio.play() : myAudio.pause()
    this.setData({
      isPlay
    })
  },
  //  跳转播放视频页
  toVideoPage() {
    const data = {
      video: this.data.detail.video,
      videoDesc: this.data.detail.videoDesc || '',
      img: this.data.detail.img || this.data.detail.image,
      name: this.data.detail.name,
    }
    wx.navigateTo({
      url: '/pages/TradingArea/videoPlay?data=' + JSON.stringify(data),
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this
    clearInterval(that.data.timer)
    clearInterval(that.data.redTimer)

    // 停止音频播放
    myAudio.stop()

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    let that = this
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      let sceneParams = scene.split(",")
      this.setData({
        couponBagId: sceneParams[1],
        invitationAccountId: sceneParams[2],
        type: parseInt(sceneParams[3]),
        shopGroupId: sceneParams[4],
        isPlayVideo: true, //扫码进入先播放视频
      })
    } else {
      this.setData({
        couponBagId: options.id,
        type: parseInt(options.type)
      })
      if (options.shopGroupId) {
        this.setData({
          shopGroupId: options.shopGroupId,
        })
      }
      if (options.goodsIndex) {
        this.setData({
          goodsIndex: options.goodsIndex,
        })
      } else {
        this.setData({
          goodsIndex: 0,
        })
      }
      if (options.invitationAccountId) {
        this.setData({
          invitationAccountId: options.invitationAccountId
        })
      }
      if (options.isFromMyCenterVideo) {
        this.setData({
          isFromMyCenterVideo: options.isFromMyCenterVideo
        })
      }

    }



    this.setData({
      timer: setInterval(function () {
        let page = getCurrentPages()
        if (page[page.length - 1].route != 'pages/TradingArea/GiftBagDetail') {
          return
        }
        // that.getMsg()
      }, 10000)
    })
    
    this.getBagActivityDetail()
    this.getUserPayPage()
    this.accountTotalRewardPage()


    if (wx.getStorageSync('usertoken')) {
      if (this.data.type == 3) {
        controller.pinList().then(res => {
          if (!this.data.redTimer) {
            this.setData({
              redTimer: setInterval(function () {
                let page = getCurrentPages()
                if (page[page.length - 1].route != 'pages/TradingArea/GiftBagDetail') {
                  return
                }
                that.pinList()
              }, 6000)
            })
          }
          if (res.data.length > 0) {
            this.setData({
              redList: res.data
            })
            if (res.data.length > 0) {
              that.setData({
                redShow: true,
                closeAnimate: true
              })
              clearInterval(that.data.redTimer)
              if (res.data[0].state == 1) {
                this.setData({
                  pinSuccess: true,
                  readPinOrderNo: this.data.redList[0].orderNo
                })
              } else {
                this.setData({
                  pinSuccess: false,
                  redId: this.data.redList[0].transactionId,
                  redPrice: this.data.redList[0].redMoney
                })
              }
            }
          }
        })
      }
    } else {
      app.usertokenReadyCallback = res => {
        if (this.data.type == 3) {
          controller.pinList().then(res => {
            if (!this.data.redTimer) {
              this.setData({
                redTimer: setInterval(function () {
                  let page = getCurrentPages()
                  if (page[page.length - 1].route != 'pages/TradingArea/GiftBagDetail') {
                    return
                  }
                  that.pinList()
                }, 6000)
              })
            }
            if (res.data.length > 0) {
              this.setData({
                redList: res.data
              })
              if (res.data.length > 0) {
                that.setData({
                  redShow: true,
                  closeAnimate: true
                })
                clearInterval(that.data.redTimer)
                if (res.data[0].state == 1) {
                  this.setData({
                    pinSuccess: true,
                    readPinOrderNo: this.data.redList[0].orderNo
                  })
                } else {
                  this.setData({
                    pinSuccess: false,
                    redId: this.data.redList[0].transactionId,
                    redPrice: this.data.redList[0].redMoney
                  })
                }
              }
            }
          })
        }
      }
    }

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let couponBagId = this.data.couponBagId
    let invitationAccountId = wx.getStorageSync('accountId')
    let title = this.data.detail.shopGroupName
    let type = this.data.type
    let url = "/pages/TradingArea/GiftBagDetail?id=" + couponBagId + "&invitationAccountId=" + invitationAccountId + "&type=" + type
    console.log(url)
    return {
      title: title,
      path: "/pages/TradingArea/GiftBagDetail?id=" + couponBagId + "&invitationAccountId=" + invitationAccountId + "&type=" + type
    }
  },

  //跳转优惠券详情
  toCouponDetail(e) {
    let id = e.currentTarget.dataset.id
    let invitationAccountId = this.data.invitationAccountId || ''
    let shopId = e.currentTarget.dataset.shopid
    let isCard = e.currentTarget.dataset.iscard
    let cardId = e.currentTarget.dataset.cardid
    if (isCard == 1) {
      wx.navigateTo({
        url: '/pages/my/vip/info/VIPCardInfo?id=' + cardId + "&shopId=" + shopId + "&notQC=1",
      });
    } else {
      wx.navigateTo({
        url: '/pages/TradingArea/couponDetail?id=' + id + '&couponBagId=' + this.data.couponBagId + "&invitationAccountId=" + invitationAccountId,
      })
    }
  },

  // 跳转亲友卡详情
  toCardDetail(event) {
    let id = event.currentTarget.dataset.id;
    let shopId = event.currentTarget.dataset.shopid
    wx.navigateTo({
      url: '/pages/my/vip/info/VIPCardInfo?id=' + id + "&shopId=" + shopId + "&notQC=1",
    });
  },

  //分享海报
  sharePoster() {
    // if (this.data.detail.isPay == false) {
    //   wx.showToast({
    //     icon: "none",
    //     title: '购买之后才能分享',
    //     duration: 1500
    //   })
    //   return
    // }   

    controller.getSharePoster({
      couponBagId: this.data.couponBagId
    }).then(res => {
      this.setData({
        shareImg: res.data,
      })
      // 加时间戳防止缓存问题，打开图片不完整
      let timestamp = Date.parse(new Date())
      let img = res.data + "?t=" + timestamp
      let list = []
      list.push(img)
      wx.previewImage({
        urls: list,
      })
    })
  },

  //返回
  backBtn(e) {
    let page = getCurrentPages()
    let isFromMyCenterVideo = this.data.isFromMyCenterVideo
    if (page.length <= 1 || isFromMyCenterVideo) { //来自个人中心活动详情视频播放页 返回至首页
      wx.redirectTo({
        url: '/pages/TradingArea/index',
      })
    } else {
      wx.navigateBack()
    }
  }
})